<template>
  <FrontSideTreeTable
    treeDataUrl="/sys/units/getList"
    tableDataUrl="/sys/units/getList"
    addUrl="/sys/units/add"
    editUrl="/sys/units/edit"
    deleteUrl="/sys/units/delete"
    treeTitle="部门"
    tableTitle="部门列表"
    searchHint="根据部门名称查找"
    :searchProps="searchProps"
    :columns="columns"
    :form="form"
    :rules="rules"
    @onTableCreated="onTableCreated"
    @onNodeClick="onNodeClick"
    @beforeAdd="beforeAdd"
    @beforeEdit="beforeEdit"
    @onManage="handleManage"
    @onGrant="handleGrant"
    manageable>
    <!--表单-->
    <template slot="form">
      <!--  新增或编辑对话框  -->
      <el-form-item label="父单位">
        <el-select v-model="form.parentId" style="width:100%" placeholder="请选择父单位，输入文字可搜索" filterable clearable>
          <el-option v-for="item of dataList" :key="item.id" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="单位名称" prop="name">
        <el-input v-model="form.name" placeholder="输入菜单名称"></el-input>
      </el-form-item>
      <el-form-item label="负责人">
        <el-input v-model="form.headPerson" placeholder="输入单位负责人姓名"></el-input>
      </el-form-item>
      <el-form-item label="联系电话" prop="tel">
        <el-input v-model="form.tel" placeholder="输入单位联系电话"></el-input>
      </el-form-item>
      <el-form-item label="备注">
        <el-input type="textarea" v-model="form.notes"></el-input>
      </el-form-item>
    </template>

    <template slot="dialog">
      <!--数据权限管理对话框-->
      <el-dialog :title="manageDialogTitle" size="tiny" v-model="isManageDialogVisible" :close-on-click-modal="false">
        <el-card class="card" v-loading="loadingAddress">
          <div slot="header">
            <span class="card-head">地区</span>
          </div>
          <el-tree
            ref="addressTree"
            class="tree-view"
            node-key="id"
            :data="addressTreeList"
            :props="treeProps"
            highlight-current
            show-checkbox
            accordion>
          </el-tree>
        </el-card>
        <!--对话框按钮区-->
        <div slot="footer" class="dialog-footer">
          <el-button @click="isManageDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="doManage" :loading="isManaging">确 定</el-button>
        </div>
      </el-dialog>

      <!--报告权限对话框-->
      <el-dialog :title="templateDialogTitle" size="tiny" v-model="isTemplateDialogVisible" :close-on-click-modal="false">
        <el-card class="card" v-loading="loadingTemplate">
          <div slot="header">
            <span class="card-head">报告模板</span>
          </div>
          <el-tree
            ref="templateTree"
            class="tree-view"
            node-key="id"
            :data="templateList"
            :props="treeProps"
            highlight-current
            show-checkbox
            accordion>
          </el-tree>
        </el-card>
        <!--对话框按钮区-->
        <div slot="footer" class="dialog-footer">
          <el-button @click="isTemplateDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="doGrantTemplate" :loading="isGrantingTemplate">确 定</el-button>
        </div>
      </el-dialog>
    </template>
  </FrontSideTreeTable>
</template>

<script>
  import FrontSideTreeTable from "../../template/FrontSideTreeTable.vue"
  import {telValidator} from "../../../assets/js/utils/ValidateUtils"
  import {clearFields} from "../../../assets/js/utils/ObjectUtils"
  import {doGet, doPost} from "../../../assets/js/utils/RequestUtils"
  import {treeOf} from "../../../assets/js/utils/TreeUtils"
  import {getAuthorizedFunction} from "../../../assets/js/global"
  import {GRANT, MANAGE} from "../../../assets/js/enum/FunctionType";

  let oldUnitsName = "";

  let selectedNodeId = "";

  const ADDRESS_URL = "/sys/units/getAddressList";

  const UNITS_ADDRESS_URL = "/sys/units/getAddressByUnitsId";

  const ADD_UNITS_ADDRESS_URL = "/sys/units/addUnitsAddress";

  const TEMPLATE_URL = "/sys/units/getTemplateList";

  const UNITS_TEMPLATE_URL = "/sys/units/getTemplateByUnitsId";

  const ADD_UNITS_TEMPLATE_URL = "/sys/units/addUnitsTemplate";

  export default {
    name:"UnitsManagement",
    data() {
      //名称唯一性校验
      let nameValidator = (rule, value, callback)=>{
        if(value === oldUnitsName) {
          callback();
        }else {
          if(this.dataList.some(item=>item.name === value)) {
            callback(new Error("单位名称重复"));
          }else {
            callback();
          }
        }
      };

      return {
        searchProps: ["name"],
        dataList: [],
        form:{
          parentId:"",
          name:"",
          headPerson:"",
          tel:"",
          notes:""
        },
        columns:[
          {prop:"name", label:"部门名称", width:"500"},
          {prop:"headPerson", label:"负责人"},
          {prop:"tel", label:"联系电话"}
        ],
        treeProps: {
          children:"children",
          label:"name"
        },
        rules:{
          name: [
            {required:true, message:"请输入部门名称", trigger:"blur"},
            {validator:nameValidator, trigger:"blur"}
          ],
          tel: [
            {validator:telValidator, trigger:"blur"}
          ]
        },
        currentUnitsId:"",
        addressList:[],
        manageDialogTitle:"",
        isManageDialogVisible:false,
        loadingAddress:false,
        isManaging:false,
        defaultCheckedTreeKeys: new Set(),
        //报告管理
        templateDialogTitle:"",
        isTemplateDialogVisible:false,
        loadingTemplate:false,
        isGrantingTemplate:false,
        templateList:[],
        templateDefaultCheckedTreeKeys: new Set()
      }
    },
    computed: {
      addressTreeList() {
        return treeOf(this.addressList);
      }
    },
    methods: {
      onTableCreated(dataList) {
        this.dataList = dataList;
      },
      onNodeClick(data) {
        selectedNodeId = data.id;
      },
      beforeAdd() {
        oldUnitsName = "";
        clearFields(this.form);
        this.form.parentId = selectedNodeId;
      },
      beforeEdit(data) {
        oldUnitsName = data.name;
        this.form = {...data};
      },
      handleManage(data) {
        this.currentUnitsId = data.id;
        this.manageDialogTitle = data.name + "——数据权限管理";
        this.isManageDialogVisible = true;
        this.loadingAddress = true;
        this.defaultCheckedTreeKeys.clear();
        this.fetchAddressData();
      },
      doManage() {
        this.isManaging = true;
        doPost(ADD_UNITS_ADDRESS_URL, {
          data:{
            unitsId: this.currentUnitsId,
            addressIds:this.$refs["addressTree"].getCheckedKeys(),
          },
          menuFunctionId:getAuthorizedFunction(this, MANAGE),
          component:this
        })
          .then(response => this.$message({message: response.message, type: response.status.toLowerCase()}))
          .finally(()=>{
            this.isManaging = false;
            this.isManageDialogVisible = false;
          });
      },
      handleGrant(data) {
        this.currentUnitsId = data.id;
        this.templateDialogTitle = data.name + "——报告模板权限管理";
        this.isTemplateDialogVisible = true;
        this.loadingTemplate = true;
        this.templateDefaultCheckedTreeKeys.clear();
        this.fetchTemplateData();
      },
      doGrantTemplate() {
        this.isGrantingTemplate = true;
        doPost(ADD_UNITS_TEMPLATE_URL, {
          data:{
            unitsId:this.currentUnitsId,
            templateIds:this.$refs["templateTree"].getCheckedKeys()
          },
          menuFunctionId:getAuthorizedFunction(this, GRANT),
          component:this
        }).then(response => this.$message({message: response.message, type: response.status.toLowerCase()}))
          .finally(()=>{
            this.isGrantingTemplate = false;
            this.isTemplateDialogVisible = false;
          });
      },
      fetchAddressData() {
        doGet(ADDRESS_URL, {component:this})
          .then(response=>{
              this.addressList = response;
              this.fetchAuthData();
          })
          .finally(()=>this.loadingAddress = false);
      },
      fetchAuthData() {
        doGet(UNITS_ADDRESS_URL, {
          data:{unitsId:this.currentUnitsId},
          component:this
        })
          .then(response=>{
            this.defaultCheckedTreeKeys = new Set(response.filter(item=>!this.addressList.some(i=>i.parentId === item.addressId)).map(item=>item.addressId));
            this.setTreeSelection();
          })
      },
      setTreeSelection() {
        if (this.$refs["addressTree"]) {
            this.$refs["addressTree"].setCheckedKeys([...this.defaultCheckedTreeKeys]);
        }
      },
      fetchTemplateData() {
        doGet(TEMPLATE_URL, {component:this})
          .then(response=>{
            this.templateList = response;
            this.fetchTemplateAuthData();
          })
          .finally(()=>this.loadingTemplate = false)
      },
      fetchTemplateAuthData() {
        doGet(UNITS_TEMPLATE_URL, {
          data:{unitsId:this.currentUnitsId},
          component:this
        }).then(response=>{
          this.templateDefaultCheckedTreeKeys = new Set(response.map(item=>item.id));
          this.setTemplateTreeSelection();
        })
      },
      setTemplateTreeSelection() {
        if (this.$refs["templateTree"]) {
          console.log(this.templateDefaultCheckedTreeKeys);
          this.$refs["templateTree"].setCheckedKeys([...this.templateDefaultCheckedTreeKeys]);
        }
      }
    },
    components: {FrontSideTreeTable}
  }
</script>

<style scoped>
  .tree-view {
    border: 0;
  }
  .card {
    margin-left: 15px;
    padding: 5px 5px 5px 5px;
  }
  .card-head {
    font-size: 1.2em;
    font-weight: bold;
  }
</style>



// WEBPACK FOOTER //
// UnitsManagement.vue?61fe6972